package netty.bio;

import io.netty.util.concurrent.DefaultThreadFactory;
import lombok.val;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author: zhangrongqing
 * @Date: 2020/1/2 15:40
 */
public class BioServer {

    //服务器通信
    public static void handle(Socket socket) throws IOException {
        byte[] bytes = new byte[1024];
        try {
            InputStream inputStream = socket.getInputStream();
            while(true){
                int read = inputStream.read(bytes);
                if(read != -1){
                    System.out.println(new String(bytes));
                }else{
                    break;
                }
            }
        }catch (Exception  e){

        }finally {
            System.out.println("关闭client连接");
            socket.close();
        }

    }


    public static void main(String[] args) throws IOException {

        ExecutorService executorService = new ThreadPoolExecutor(10,10,0, TimeUnit.SECONDS
                ,new ArrayBlockingQueue<>(10),new DefaultThreadFactory("test"));

        ServerSocket serverSocket = new ServerSocket(9090);
        System.out.println("服务器启动");
        while (true){
            //等待监听
            Socket socket = serverSocket.accept();
            System.out.println("客户端启动");

            executorService.execute(() -> {
                try {
                    BioServer.handle(socket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}
